package Nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Vector;

/**
 * @author jou
 */
public class NioServer {
    static String host = "127.0.0.1";
    static int port = 1180;
    static Vector<SocketChannel> channels = new Vector<>();
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocket = ServerSocketChannel.open();
            SocketAddress socketAddress = new InetSocketAddress(host, port);
            serverSocket.bind(socketAddress);
            serverSocket.configureBlocking(false);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (true) {
                for (SocketChannel el : channels) {
                    int read = el.read(buffer);
                    if (read > 0) {
                        System.out.println("read--");

                        buffer.flip();
                        byte[] bs = new byte[read];
                        buffer.get(bs);
                        String content = new String(bs);
                        System.out.println(content);
                        buffer.flip();
                    }
                    if (read < 0) {
                        el.close();
                        channels.remove(el);
                        System.out.println("close conn!");
                    }
                }
                SocketChannel accept = serverSocket.accept();
                if (accept != null) {
                    System.out.println("conn --");
                    accept.configureBlocking(false);

                    channels.add(accept);
                    System.out.println("conn: " + channels.size());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
